import React, { useState, useRef } from 'react';
import { Tree, Spin, Space, Image, Empty, Button, message, } from 'antd';
import { DeleteOutlined, EditOutlined, LeftCircleOutlined, RightCircleOutlined } from '@ant-design/icons'
import styles from './index.module.less'
import useTreeData from './getTreeData'
import { getBLDetail, deleteBL, deleteJYJG } from '@/services/mz'
import { getBLDetail as getZYBLDetail, deleteBL as deleteZYBL, deleteJYJG as deleteZYJYJG } from '@/services/zy'
import store from '@/store';

import AddModal from '@/components/Modal/AddModal';
import EditMedical from '@/components/EditMedical';
import showDeleteConfirm from '@/utils/deleteConfirm';
import { exportWord } from '@/utils/download'
import WithAuthComp from '@/components/WithAuthComp';
import { ROLE } from '@/common/const'
import { formatImgsArr } from '@/utils/format'

enum CurrentType {
    BL = 'bl',
    IMG = 'img'
}

type Props = {
    id: string
    type: 'mz' | 'zy'
    editable: boolean
}

const MedicalDetail: React.FC<Props> = (props) => {
    const { id, type, editable } = props
    const blDetailApi = type === 'mz' ? getBLDetail : getZYBLDetail
    const deleteBlApi = type === 'mz' ? deleteBL : deleteZYBL
    const deleteJYJGApi = type === 'mz' ? deleteJYJG : deleteZYJYJG

    const { treeData, loading, refresh } = useTreeData(id, type)
    const [currentType, setCurrentType] = useState(CurrentType.BL)
    const [selectedKeys, setSelectedKeys] = useState<string[]>([])
    const [result, setResult] = useState<any>()
    const [detailLoading, setDetailLoading] = useState(false)
    const [selectedNode, setSelectedNode] = useState<any>('')
    const addMedicalRef = useRef<any>()
    const [userState] = store.useModel('user');

    const getContentById = async (blId, node) => {
        let result;
        setDetailLoading(true)
        if (node.type === CurrentType.BL) {
            result = await blDetailApi({ blId: blId, recordId: id })
        } else {
            result = { data: node.url }  // 图片在构造树列表的时候已经返回了，因此直接去节点数据即可
        }
        if (Array.isArray(result.data)) {
            let totalString = ''
            result.data.forEach(item => {
                totalString += item.content + '<br />'
            })
            setResult({ content: totalString })
        } else {
            setResult(result.data)
        }
        setCurrentType(node.type)
        setDetailLoading(false)
    }

    const onSelect = async (selectedKeys, info) => {
        const id = selectedKeys[0];
        if (!id) return
        setSelectedKeys([id]);
        setSelectedNode(info.node);
        await getContentById(id, info.node)
    };

    const handleSaveBl = async () => {
        addMedicalRef?.current?.hideModelRef();
        await getContentById(selectedKeys[0], selectedNode)
    }

    const titleRender = (node) => {
        const handleEdit = (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            // 防止病例未加载就被编辑做的hack操作
            if (node.key != selectedKeys[0]) {
                message.warning('请先查看病例后再编辑！')
                return
            }
            addMedicalRef?.current?.showModelRef();
        }
        const handleDelete = (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            if (node.key != selectedKeys[0]) {
                message.warning('请先查看后再删除！')
                return;
            }
            showDeleteConfirm({
                id: node.key,
                deleteApi: node.type === CurrentType.BL ? deleteBlApi : deleteJYJGApi,
                cb: () => {
                    setSelectedKeys([]);
                    setResult(null);
                    refresh();
                }
            })
        }
        const canEdit = () => {
            return (userState.currentUser.jobnumber === node.createJnumber || userState.currentUser.jobnumber === 'admin') && node.type === CurrentType.BL && node.canEdit && editable
        }
        return <Space className={styles.titleContainer}>
            <span>{node.title}</span>
            {node.key === '0-1' || node.key === '0-0' ? null :
                (
                    <div className={styles.tools}>
                        {/* 病历并非住院状态并且无子病历才可编辑 */}
                        {canEdit() && <WithAuthComp authKey={[ROLE.YS, ROLE.HS]}><EditOutlined onClick={handleEdit} style={{ marginRight: '5px' }} /></WithAuthComp>}
                        {!node.isDir && <WithAuthComp authKey={[ROLE.ADMIN]}><DeleteOutlined onClick={handleDelete} /></WithAuthComp>}
                    </div>
                )
            }
        </Space>
    }

    const handlePre = () => {
        if (selectedKeys.length === 0) return
        const jyjg = formatImgsArr(treeData[treeData.length - 1].children)
        const index = jyjg?.findIndex(item => item.key === selectedKeys[0]) || 0
        if (index === 0) {
            message.warning('已经是第一个了！')
            return
        }
        onSelect([jyjg[index - 1].key], { node: jyjg[index - 1] })
    }
    const handleNext = () => {
        if (selectedKeys.length === 0) return
        const jyjg = formatImgsArr(treeData[treeData.length - 1].children)
        const index = jyjg?.findIndex(item => item.key === selectedKeys[0]) || 0
        if (index === jyjg.length - 1) {
            message.warning('已经是最后一个了！')
            return
        }
        onSelect([jyjg[index + 1].key], { node: jyjg[index + 1] })
    }

    return (
        <div className={styles.medicalDetail}>
            <div className={styles.left}>
                {
                    loading ? <Spin /> : <Tree
                        titleRender={titleRender}
                        defaultExpandedKeys={['0-0', '0-1']}
                        onSelect={onSelect}
                        treeData={treeData}
                        selectedKeys={selectedKeys}
                    />
                }
            </div>
            <div className={styles.right}>
                <Spin spinning={detailLoading}>
                    {result ?
                        currentType === CurrentType.BL ? <div className={styles.htmlContainer}>
                            <div className={styles.content} dangerouslySetInnerHTML={{ __html: result?.content }}>
                            </div>
                            <div className={styles.btn}>
                                <Button type='primary' onClick={() => exportWord(result.content, selectedNode.title)}>导出</Button>
                            </div>
                        </div> :
                            <div className={styles.imgContainer}>
                                <LeftCircleOutlined className={`${styles.imgBtn} ${styles.leftBtn}`} onClick={handlePre} />
                                <Image src={result} alt="检验结果" className={styles.resultImg} width={512} height={512} placeholder={
                                    <Spin delay={200} size='large' tip="图片加载中">
                                        <div style={{ width: '512px', height: '512px' }}>
                                        </div>
                                    </Spin>
                                } />
                                <RightCircleOutlined className={`${styles.imgBtn} ${styles.rightBtn}`} onClick={handleNext} />
                            </div>
                        : <Empty description="暂无数据" />}
                </Spin>
            </div>

            <AddModal ref={addMedicalRef} title='' width="80%">
                <EditMedical id={selectedKeys[0]} onSave={handleSaveBl} content={result?.content} />
            </AddModal>
        </div>
    );
};

export default MedicalDetail;